package com.woniu.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhaolei
 * @date 2021/5/7 - 23:40
 */
public class ThreadDemo4 implements Runnable{
    private static int num = 20;    //设置静态资源实现共享
    private  Lock lock = new ReentrantLock();

        public void sale(){
            lock.lock();
            try{
                if (num > 0){           //判断库中是否还有余票
                    System.out.println(Thread.currentThread().getName() +
                            "--卖出了第" + (num--) + "张票");
                    try {
                        Thread.sleep(1000); //设定耗时时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    System.out.println("票已售完");
                }

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    public void run() {
       //模拟票超出购买数量了
        sale();
    }
}
